package com.fileshare.web.controller.index.view;

import com.fileshare.web.controller.index.BaseController;
import com.fileshare.web.service.LoginService;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
    private static final String INDEX = "/index";
    @Resource
    private LoginService loginService;

    @GetMapping("")
    public String login() {
        return view("login/index");
    }

    @RequestMapping("/{source}")
    public void renderAuth(@PathVariable String source, HttpServletResponse response,
                           HttpServletRequest request) throws IOException {
        if (loginService.loginBefore(request)) {
            response.sendRedirect(INDEX);
        } else {
            AuthRequest authRequest = loginService.getAuthRequest(source);
            String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
            response.sendRedirect(authorizeUrl);
        }
    }

    @RequestMapping("/callback/{source}")
    public void login(@PathVariable String source, AuthCallback callback,
                      HttpServletResponse response, HttpServletRequest request) throws IOException {
        if (loginService.thirdPartyLogin(source, callback, request)) {
            response.sendRedirect(INDEX);
        } else {
            response.sendRedirect("/login/" + source);
        }
    }

    @RequestMapping("/out")
    public void out(HttpServletResponse response, HttpServletRequest request) throws IOException {
        loginService.loginOut(request);
        response.sendRedirect(INDEX);

    }
}